<template>
  <div class="container writeAns">
      <img src='/static/images/1.png' class='tuoyuan'  mode="aspectFill"/>
      <div class="questionBox">
          <classTit title="问题"></classTit>
          <div>
              <div class="comment">
                <span>Q：</span>{{wenda.questions}}
              </div>
              <div class="imgs">
                    <img :src="item" alt=""  mode="aspectFill" v-for="item in wenda.images" :key="item" />
              </div>
          </div>
          <div class="weui-cell" style="padding-left:50rpx"> <voice v-if="wenda.audio" :audio="wenda.audio"/></div>
      </div>
      <div class="answerBox">
         <classTit title="答案"></classTit>
         <textarea class="weui-textarea" name="content"  placeholder="写答案.." v-model="question.content" />
         <div class='images' >
           <div class='imageItem' v-for="(item,index) in upImgs" :key="index">
              <img class='thumb' :src="ylink+item" mode="aspectFill"/>
              <img class='close' src='/static/images/close.png' @click='delImg'/>
           </div>
        </div> 
        <div class="weui-cell">
            <voice v-if="upaudio" :audio="audio"/>
        </div>
        <div class='answeroperate'>
            <img src='/static/images/thumb.png' @click='choose'/>
            <img src='/static/images/voice.png' @click='record'/>
        </div> 
      </div>
      <div class='record'  v-show='ly.LYstart'>
       <div class='title' @click='cencel'>取消</div>
       <div class='tu'>
          <img src='/static/images/LY.png' @click='start'/>
          <div class='zi'>点击图标开始录音</div>      
       </div>
    </div>
    <div class='record'  v-show='ly.LYend'>
       <div class='title'  @click='cencel'>取消</div>
       <div class='tu'>
          <img src='/static/images/LY1.png'  @click='stop'/>
          <text class='Ytime'>{{numVal}}</text>
          <div class='zi'>点击结束录音</div>      
       </div>
    </div>
    <div class='record' v-show='ly.upload'>
       <div class='title weui-cell'>
          <div class='weui-cell__bd'  @click='cencel'>取消</div>
          <div class='weui-cell__ft' style='color:#46B7FF'  @click='uploadLy'>上传</div>
       </div>
       <div class='tu'>
          <img src='/static/images/LY2.png'  @click='play'/>
          <text class='Ytime'>{{numVal}}</text>
          <!-- <div class='zi zi1'  @click='afresh'>重新录制</div>       -->
       </div>
    </div>
    <div class="mark" v-show="mask"></div>
      <div class="kong"></div>
      <div class="footer" @click="toanswer">发表</div>      
  </div>
</template>

<script>
const recorderManager = wx.getRecorderManager()
const innerAudioContext = wx.createInnerAudioContext()
import classTit from "@/components/classTit";
import voice from "@/components/voice"
import {comment} from "@/api/operate"
var quesId;
import URL from "@/utils/host";
export default {
  
  components: {
    classTit,
    voice
  },

  data () {
    return {
       wenda:{},
       question:{},
       upImgs:[],
       ylink: URL.host3,
       ly:{
          LYstart:false,
          LYend:false,
          upload:false
       },
       mask:false,
       num: 1,
       numVal: 1 + '"',
       setInter:"",
       audios:"",
       upaudio:false,
    }
  },
  methods:{
      record:function(){
          this.ly={
              LYstart:true,
              LYend:false,
              upload:false
          }
          this.mask=true
      },
      cencel(){
          this.ly={
              LYstart:false,
              LYend:false,
              upload:false   
          }
          this.mask=false
      },
      start(){
        var that=this;
         const options = {
                duration: 10000,//指定录音的时长，单位 ms
                sampleRate: 16000,//采样率
                numberOfChannels: 1,//录音通道数
                encodeBitRate: 96000,//编码码率
                format: 'mp3',//音频格式，有效值 aac/mp3
                frameSize: 50,//指定帧大小，单位 KB
            }
            //开始录音
            recorderManager.start(options);
            recorderManager.onStart((res) => {
                console.log('recorder start')
                that.startSetInter()
                that.ly={
                    LYstart:false,
                    LYend:true,
                    upload:false   
                }
            });

            //错误回调
            recorderManager.onError((res) => {
               console.log(res);
            })
      },
      startSetInter: function () {
          var that = this;
          //将计时器赋值给setInter
          that.setInter = setInterval(
          function () {
              var num = that.num + 1;
              var numVal = that.formatSeconds(that.num + 1);
              that.num= num,
              that.numVal= numVal
              console.log('setInterval==' + that.num);
          }
          , 1000);
      },
      endSetInter: function () {
            var that = this;
            //清除计时器  即清除setInter
            console.log(1)
            clearInterval(that.setInter)
        },
         formatSeconds: function (value) {
            var theTime = parseInt(value);// 秒
            var middle = 0;// 分
            var hour = 0;// 小时

            if (theTime > 60) {
            middle = parseInt(theTime / 60);
            theTime = parseInt(theTime % 60);
            if (middle > 60) {
                hour = parseInt(middle / 60);
                middle = parseInt(middle % 60);
            }
            }
            var result = "" + parseInt(theTime) + '"';
            if (middle > 0) {
            result = "" + parseInt(middle) + "'" + result;
            }
            if (hour > 0) {
            result = "" + parseInt(hour) + "h" + result;
            }
            return result;
        },
        play: function () {
            var that = this;
            var ypp = that.audios;
            console.log(ypp)
            
            innerAudioContext.autoplay = true
            innerAudioContext.src = ypp,
            innerAudioContext.onPlay(() => {
                console.log('开始播放')
            })
            innerAudioContext.onError((res) => {
            console.log(res.errMsg)
            console.log(res.errCode)
            })
        },
        stop:function () {
            var that=this
            that.ly={
              LYstart:false,
              LYend:false,
              upload:true   
          }
            recorderManager.onFrameRecorded((res) => {
                console.log(res)
                const { frameBuffer } = res
                console.log('frameBuffer.byteLength', frameBuffer.byteLength)
            })
            recorderManager.stop();
            recorderManager.onStop((res) => {
                this.endSetInter()
                this.tempFilePath = res.tempFilePath;
                console.log('停止录音', res.tempFilePath)
                that.audios=res.tempFilePath
            })
        },
        uploadLy(){
          console.log(1)
          var that=this;
            wx.uploadFile({
                url: URL.host2 + "file/upload",
                filePath: that.audios,
                name: "file",
                formData: {
                  type: 1
                },
                header: {
                  Authorization: wx.getStorageSync("token"),
                  "Content-Type": "multipart/form-data"
                },
                success: res => {
                    wx.showToast({
                      title: '上传成功',
                      icon:"none"
                    }); 
                    that.wenda.audio=JSON.parse(res.data).data
                    that.upaudio=true;
                    that.ly={
                        LYstart:false,
                        LYend:false,
                        upload:false   
                    }
                    that.mask=false
                }
            });
        },
      choose: function () {
          wx.chooseImage({
            count: 1,
            sizeType: ["original", "compressed"],
            sourceType: ["album", "camera"],
            success: res => {
              wx.uploadFile({
                url: URL.host2 + "file/upload",
                filePath: res.tempFilePaths[0],
                name: "file",
                formData: {
                  type: 1
                },
                header: {
                  Authorization: wx.getStorageSync("token"),
                  "Content-Type": "multipart/form-data"
                },
                success: res => {
                  let img=JSON.parse(res.data).data
                  console.log(img)
                  this.upImgs.push(img) 
                  console.log(this.upImgs);
                }
              });
            }
          });
      },
      delImg:function(index){
          this.upImgs.splice(index, 1)
      },
      toanswer:function(){
        console.log(this.upImgs)
        let ans=this.question;
            ans.article_id=this.wenda.id;
            ans.model=1; 
            ans.type=this.wenda.article_type; 
            ans.images=this.upImgs.join(",");
            ans.audio=this.wenda.audio
        if(ans.content==undefined||ans.content.length==0){
            wx.showToast({
              title: '填写文字说明',
              icon:"none"
            });  
        }else{
          console.log(ans)
          comment(ans).then(res=>{
              let msg=res.msg;
              if(res.code==200){
                  wx.showToast({
                    title: msg,
                    icon: 'success',
                    duration: 1500,
                    mask: false,
                    success: (result) => {
                      mpvue.navigateBack({
                        delta: 1
                      });
                    },
                    fail: () => {},
                    complete: () => {}
                });
              }
          }) 
        }
          
      }
  },
  created () {
     
  },
  onLoad(options){
       Object.assign(this.$data, this.$options.data())
      let wenda=JSON.parse(options.wenda)
      this.wenda=wenda;
      
  }
}
</script>
<style lang="scss">
   .writeAns{
       .classTit{
           padding-left: 0;
           margin-top: 0;
       }
   }
</style>
<style scoped lang="scss">
.tuoyuan{
    width: 375px;
    height: 118px;
    display: block;
    position: absolute;
    top: 0;
    left: 0;
}
.questionBox{
    width:345px;
    min-height:145px;
    background:rgba(255,255,255,1);
    box-shadow:0px 0px 8px 0px rgba(0, 0, 0, 0.14);
    border-radius:5px;
    margin: 15px auto;
    position: relative;
    padding-top: 12px;
    padding-bottom: 12px;
}
.comment {
  padding: 8px 25px;
  font-size: 14px;
  color: #333;
  line-height: 21px;
  span {
    color: rgba(233, 181, 94, 1);
    font-weight: bold;
  }
}
.imgs{

   padding-left:25px;
   img{
      width:90px;
      height:90px;
      margin-right: 8px;
   }
}
.answerBox{
  width:345px;
  background:rgba(255,255,255,1);
  box-shadow:0px 0px 8px 0px rgba(0, 0, 0, 0.14);
  border-radius:5px;
  padding-top:10px;
  margin:auto;
  position: relative;
  textarea{
    padding:10px 25px;
    box-sizing: border-box;
    min-height: 140px;
    font-size: 14px;
    color: #333;
    line-height: 21px;
  }
  .images{
    padding:0 20px;
     .imageItem{
        width:70px;
        height:70px;
        background:rgba(239,239,239,1);
        display: inline-block;
        position: relative;
        .thumb{
          width:70px;
          height:70px;
          display: block;
        }
        .close{
          width:18px;
          height:18px;
          position: absolute;
          top:-9px;
          right:-9px;
          display: block;

        }
     }
  }
  .answeroperate{
    padding-top:0;
    padding-bottom:15px;
    font-size:24rpx;
    font-weight:500;
    color:rgba(102,102,102,1);
    img{
      width:28px;
      height:28px;
      margin-left:20px;
    }
  }
}

  .kong{
    height:50px;
  }
  .footer{
      position: fixed;
      left: 0;
      right:0;
      bottom:0;
      width:375px;
      height:45px;
      background:#1B84FB;
      text-align:center;
      line-height:45px;
      font-size:15px;
      font-weight:bold;
      color:rgba(255,255,255,1);
  }

.record{
  width:750rpx;
  height:347rpx;
  background:rgba(255,255,255,1);
  position: fixed;
  left: 0;
  right: 0;
  bottom: 0;
  z-index: 2;
  .tu{
    position: relative;
    img{
      width: 124rpx;
      height: 124rpx;
      display: block;
      margin: 0 auto;
      margin-top: 40rpx;
    }
    .Ytime{
      position: absolute;
      top: 0;
      left: 50%;
      margin-left:70rpx; 
      font-size:28rpx;
      font-weight:500;
      color:rgba(70,183,255,1);
    }
  } 
  .title{
    font-size:30rpx;
    font-weight:500;
    color:rgba(102,102,102,1);
    padding: 10px 15px;
  }
  .tu .zi{
    text-align: center;
    font-size:28rpx;
    font-weight:500;
    color:rgba(102,102,102,1);
    line-height: 2;
  }
  .tu .zi1{
    padding: 10px 15px;
    text-align: right;
  }
}
.mark{
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0,0 , 0, 0.5)
}

</style>
